<!--
 * @Description: 生成海报组件
 * @Version: 1.0.0
 * @Autor: hch
 * @Date: 2020-08-07 14:48:41
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-07-31 18:11:35
 * 保存海报按钮和关闭按钮 在html代码中写出来 绑定点击方法然后透明 再用canvas 覆盖
-->

<template>
	<view class="canvas-content" v-show="canvasShow" :style="'width:' + system.w + 'px; height:' + system.h + 'px;'">
		<!-- 遮罩层 -->
		<view class="canvas-mask"></view>
		<!-- 海报 -->
		<!-- :width="system.w" :height="system.h" 支付宝必须要这样设置宽高才有效果 -->

		<canvas class="canvas" canvas-id="myCanvas" id="myCanvas"
			:style="'width:' + system.w + 'px; height:' + system.h + 'px;'" :width="system.w"
			:height="system.h"></canvas>
		<view :class="imgShow?'canvas_ canvas_add':'canvas_'">
			<image show-menu-by-longpress id="myCanvas" @load="load"
				:style="'width:' + 220 + 'px;'" :src="imageCode" mode="widthFix"></image>
			<view class="">
				长按分享
			</view>
		</view>


		<view class="button-wrapper" v-if="false">
			<!-- 保存海报按钮 -->
			<!-- #ifndef MP-QQ -->
			<!-- cover-view 标签qq小程序有问题 -->
			<cover-view class="save-btn" @tap="saveImage">保存海报</cover-view>
			<cover-view class="save-btn cancel-btn" @tap="handleCanvasCancel">取消</cover-view>
			<!-- #endif -->
			<!-- #ifdef MP-QQ -->
			<view class="save-btn" @tap="saveImage">保存海报</view>
			<view class="save-btn cancel-btn" @tap="handleCanvasCancel">取消</view>
			<!-- #endif -->
		</view>

	</view>
</template>

<script>
	import {
		drawSquarePic,
		drawTextReturnH,
		getSystem
	} from './utils'
	let animation = uni.createAnimation({
		duration: 1500,
		timingFunction: 'ease',
		delay: 0
	});
	export default {
		data() {
			return {
				system: {},
				canvasShow: false,
				show: false,
				imgShow: false,
				imageCode: ''
			}
		},
		props: {
			posterData: {
				type: Object,
				default: () => {
					return {}
				}
			}
		},
		computed: {
			/**
			 * @description: 计算海报背景数据
			 * @param {*}
			 * @return {*}
			 * @author: hch
			 */

			poster() {
				let data = this.posterData
				let system = this.system

				let posterBg = {
					url: data.poster.url,
					r: data.poster.r * system.scale,
					w: data.poster.w * system.scale,
					h: data.poster.h * system.scale,
					x: (system.w - data.poster.w * system.scale) / 2,
					y: (system.h - data.poster.h * system.scale) / 2,
					p: data.poster.p * system.scale
				}
				return posterBg
			},

			codeImg() {
				let data = this.posterData
				let system = this.system
				let posterCode = {
					url: data.codeImg.url,
					r: 0,
					w: data.codeImg.w * system.scale,
					h: data.codeImg.h * system.scale,
					x: (system.w + data.codeImg.w * system.scale) / 2 - 20,
					y: data.codeImg.mt * system.scale //y需要加上绘图后文本的y
				}
				return posterCode
			}
		},
		created() {
			// 获取设备信息
			this.system = getSystem()
			// this.system.w=125
			//  this.system.h=270

		},
		methods: {
			load() {
				this.imgShow = true
			},
			/**
			 * @description: 展示海报
			 * @param {type}
			 * @return {type}
			 * @author: hch
			 */
			posterShow() {
				this.canvasShow = true
				this.creatPoster()
			},
			/**
			 * @description: 生成海报
			 * @author: hch
			 */
			async creatPoster() {
				uni.showLoading({
					title: '生成海报中...'
				})
				const ctx = uni.createCanvasContext('myCanvas', this)
				this.ctx = ctx
				ctx.clearRect(0, 0, this.system.w, this.system.h) //清空之前的海报
				ctx.draw() //清空之前的海报
				// 根据设备屏幕大小和距离屏幕上下左右距离，及圆角绘制背景
				ctx.setFillStyle('rgba(0,0,0,0)')
				let title = this.title
				let poster = this.poster
				let codeImg = this.codeImg

				let address = this.address
				let phone = this.phone
				await drawSquarePic(ctx, poster.x, poster.y, poster.w, poster.h, poster.r, poster.url)

				// 绘制标题 textY 绘制文本的y位置
				console.log('creatPoster -> name.x')




				// 绘制小程序码
				// await drawSquarePic(
				//   ctx,
				//   187-codeImg.w/2,
				//   poster.y+160,
				//   codeImg.w, 
				//   codeImg.h,
				//   codeImg.r,
				//   codeImg.url
				// ) 


				this.$emit('succeed')

				this.show = true
				setTimeout(() => {
					this.handleSaveCanvasImage()
				}, 100)

			},
			/**
			 * @description: 保存到系统相册
			 * @param {type}
			 * @return {type}
			 * @author: hch
			 */
			saveImage() {
				let _this = this
				uni.saveImageToPhotosAlbum({
					filePath: _this.imageCode,
					success(res) {
						uni.hideLoading()
						uni.showToast({
							title: '图片保存成功，可以去分享啦~',
							duration: 2000,
							icon: 'none'
						})
						_this.handleCanvasCancel()

					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							title: '保存失败，稍后再试',
							duration: 2000,
							icon: 'none'
						})
						uni.hideLoading()
						if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg ===
							"saveImageToPhotosAlbum:fail auth deny" || err.errMsg ===
							"saveImageToPhotosAlbum:fail authorize no response") {
							// 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
							wx.showModal({
								title: '提示',
								content: '需要您授权保存相册',
								showCancel: false,
								success: modalSuccess => {
									wx.openSetting({
										success(settingdata) {
											console.log("settingdata", settingdata)
											if (settingdata.authSetting[
													'scope.writePhotosAlbum']) {
												wx.showModal({
													title: '提示',
													content: '获取权限成功,再次点击图片即可保存',
													showCancel: false,
												})
											} else {
												wx.showModal({
													title: '提示',
													content: '获取权限失败，将无法保存到相册哦~',
													showCancel: false,
												})
											}
										},
										fail(failData) {
											console.log("failData", failData)
										},
										complete(finishData) {
											console.log("finishData", finishData)
										}
									})
								}
							})
						}
					}
				})

			},
			handleSaveCanvasImage() {
				// uni.showLoading({
				//   title: '保存中...'
				// })
				let _this = this
				// 把画布转化成临时文件
				// #ifndef MP-ALIPAY
				// 支付宝小程序外，其他都是用这个方法 canvasToTempFilePath
				uni.canvasToTempFilePath({
						x: this.poster.x,
						y: this.poster.y,
						width: this.poster.w, // 画布的宽
						height: this.poster.h, // 画布的高
						destWidth: this.poster.w * 5,
						destHeight: this.poster.h * 5,
						canvasId: 'myCanvas',
						quality: 1,
						success(res) {

							console.log(res.tempFilePath)
							_this.imageCode = res.tempFilePath
							uni.hideLoading()
						},
						fail(res) {
							console.log('fail -> res', res)
							uni.showToast({
								title: '保存失败，稍后再试',
								duration: 2000,
								icon: 'none'
							})
							uni.hideLoading()
						}
					},
					this
				)
				// #endif
				// #ifdef MP-ALIPAY
				// 支付宝小程序条件下 toTempFilePath
				this.ctx.toTempFilePath({
						x: this.poster.x,
						y: this.poster.y,
						width: this.poster.w, // 画布的宽
						height: this.poster.h, // 画布的高
						destWidth: this.poster.w * 5,
						destHeight: this.poster.h * 5,
						success(res) {
							//保存图片至相册
							my.saveImage({
								url: res.apFilePath,
								showActionSheet: true,
								success(res) {
									uni.hideLoading()
									uni.showToast({
										title: '图片保存成功，可以去分享啦~',
										duration: 2000,
										icon: 'none'
									})
									_this.handleCanvasCancel()
								},
								fail() {
									uni.showToast({
										title: '保存失败，稍后再试',
										duration: 2000,
										icon: 'none'
									})
									uni.hideLoading()
								}
							})
						},
						fail(res) {
							console.log('fail -> res', res)
							uni.showToast({
								title: '保存失败，稍后再试',
								duration: 2000,
								icon: 'none'
							})
							uni.hideLoading()
						}
					},
					this
				)
				// #endif
			},
			/**
			 * @description: 取消海报
			 * @param {type}
			 * @return {type}
			 * @author: hch
			 */
			handleCanvasCancel() {
				this.canvasShow = false
				this.$emit('cancel', true)
			}
		}
	}
</script>

<style lang="scss">
	.content {
		height: 100%;
		text-align: center;
	}


	.canvas-content {
		position: absolute;
		top: calc(100vmin / 7.5);

		.canvas-mask {
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			z-index: 9;
			width: 100%;
			height: 100%;
			background: rgba(0, 0, 0, 0.5);
		}

		.canvas {
			z-index: -10;
			top: -99999px;
			transform: translateY(calc(-100vmin / 7.5));

		}

		.canvas_ {
			z-index: 10;
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%) rotateY(0deg) scale(0);
transition: all 2s;
			image {
				width: 100%;
				height: 100%;
			}

			view {
				font-size: calc(26vmin / 7.5);
				color: #ffffff;
				position: absolute;
				bottom: calc(-40vmin / 7.5);
				text-align: center;
				width: 100%;
			}

		}
		.canvas_add{
			transform:translate(-50%, -50%) rotateY(720deg)  scale(1);
		}

		.button-wrapper {
			position: fixed;
			bottom: calc(20vmin / 7.5);
			z-index: 16;
			display: flex;
			width: 100%;
			height: calc(72vmin / 7.5);
			justify-content: space-around;
		}

		.save-btn {
			z-index: 16;
			width: 40%;
			height: 100%;
			font-size: calc(30vmin / 7.5);
			line-height: calc(72vmin / 7.5);
			color: #fff;
			text-align: center;
			background: $theme-color;
			border-radius: calc(45vmin / 7.5);
			border-radius: calc(36vmin / 7.5);
		}

		.cancel-btn {
			color: $theme-color;
			background: #fff;
		}

		.canvas-close-btn {
			position: fixed;
			top: calc(30vmin / 7.5);
			right: 0;
			z-index: 12;
			width: calc(60vmin / 7.5);
			height: calc(60vmin / 7.5);
			padding: calc(20vmin / 7.5);
		}
	}
</style>
